var that = null;
var strChineseFirstPY = "";
var oMultiDiff = {};
App({
  globalData: {
    isAddsuper:{},  //进入首页时，是否打开添加供应商的相关弹窗
    appId:'',
    secret:'',
    list: [], // tabBar
    dingDan: [],
    userInfo: null,
    loginInfo: null,
    openid: '', //返回openid
    phone: '',
    session_key: '',
    code: '',
    url: 'https://www.xiaobangcai.com/',
    imgSrc: '',
    imgSrc2: '',
    imgSrc3:'',
    type: 'normal',
    ShareOpenid: '', //分享者openid
    change:false,
    test:0,  //0为正常，"1"为体验者状态
    changyong_show:0, //返回商品详情页面和收藏页面是否需要刷新
    dingdan_show:0,   //返回订单页面是否需要刷新
    prevPage:'' //检测收藏页是否从购物车返回
  },
  onLaunch(options) {
    that = this;
    var info;
    var CustomBar;
    wx.getSystemInfo({
      success: e => { 
         // 获取右上角胶囊的位置信息
         info = wx.getMenuButtonBoundingClientRect();
         CustomBar = info.bottom + info.top - e.statusBarHeight
         if((e.model).substr(0,6)=='iPhone'){
          that.globalData.phonetype=true;
         };
         that.globalData.CustomBar=CustomBar;
         that.globalData.Capsule=info.top;   //胶囊顶部
         that.globalData.CapsuleWid=info.width;   //胶囊宽度
         that.globalData.Capsulehei=info.height;   //胶囊高度
      }
    });
    that.userStatus();
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    that.autoUpdate();
    that.screenSize();
  },
  autoUpdate() {
    var self = this
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //1. 检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function(res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          //2. 小程序有新版本，则静默下载新版本，做好更新准备
          updateManager.onUpdateReady(function() {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function(res) {
                if (res.confirm) {
                  //3. 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                } else if (res.cancel) {
                  //如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                  wx.showModal({
                    title: '温馨提示~',
                    content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                    success: function(res) {
                      self.autoUpdate()
                      return;
                      //第二次提示后，强制更新                      
                      if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                      } else if (res.cancel) {
                        //重新回到版本更新提示
                        self.autoUpdate()
                      }
                    }
                  })
                }
              }
            })
          })
          updateManager.onUpdateFailed(function() {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //当前用户的状态
  userStatus: function() {
    that = this;
    wx.request({
      url: 'https://www.xiaobangcai.com/get_appid_secret/xd',
      method: 'GET',
      data: {},
      success: function(res) {
        console.log(JSON.stringify(res.data));
        that.globalData.appId=res.data.appId;
        that.globalData.secret=res.data.secret;
        wx.login({
          success: function(res) {
            that.globalData.code = res.code;
            that.AppHttp("api/Client/getClientOpenId", {
              appId: that.globalData.appId,
              secret: that.globalData.secret,
              code: res.code
            }, function(res) {
              that.globalData.openid = res.data.openid;
              that.globalData.session_key = res.data.session_key;
              that.globalData.unionid = res.data.unionid;
              that.AppHttp('api/Client/personalBasic', {
                openid: res.data.openid
              }, function(res) {
                console.log(JSON.stringify(res.data));
                var data = res.data;
                that.globalData.person_id = data.data.id;   //用户个人id
                if(that.globalData.type=='jkd'){  //结款单详情
                  return;
                }else if (that.globalData.type == 'invite') { //如果是邀请的   
                  return;
                } else { //如果不是被邀请的
                  if(data.status == 1){
                    if (data.data.phone.length ==11 && data.data.client_id > 0 && data.data.is_validate == 0){
                      // 申请加入已有门店，但还未通过申请
                      wx.redirectTo({
                        url: '/pages/about/tosheqing/tosheqing'
                      })
                    }
                  }
                }
              })
            });
          }
        })
      }
    });
  },
  // 获取oMultiDiff，strChineseFirstPY
  strChineseFirstPY_oMultiDiff(){
    that.AppHttp('agreemanage/oMultiDiff.json',{}, function(res) {
      oMultiDiff=res.data;    
    });
    that.AppHttp('agreemanage/strChineseFirstPY.json',{}, function(res) {
      strChineseFirstPY=res.data;    
    });
  },
  //参数,中文字符串  
  //返回值:拼音首字母串数组  
  makePy: function(str) {
    if (typeof(str) != "string")
      throw new Error(-1, "函数makePy需要字符串类型参数!");
    var arrResult = new Array(); //保存中间结果的数组  
    for (var i = 0, len = str.length; i < len; i++) {
      //获得unicode码  
      var ch = str.charAt(i);
      //检查该unicode码是否在处理范围之内,在则返回该码对映汉字的拼音首字母,不在则调用其它函数处理  
      arrResult.push(that.checkCh(ch));
    }
    //处理arrResult,返回所有可能的拼音首字母串数组  
    that.globalData.pinyin = that.mkRslt(arrResult);
    return that.mkRslt(arrResult);
  },
  checkCh: function(ch) {
    var uni = ch.charCodeAt(0);
    //如果不在汉字处理范围之内,返回原字符,也可以调用自己的处理函数  
    if (uni > 40869 || uni < 19968)
      return ch; //dealWithOthers(ch);  
    //检查是否是多音字,是按多音字处理,不是就直接在strChineseFirstPY字符串中找对应的首字母  
    return (oMultiDiff[uni] ? oMultiDiff[uni] : (strChineseFirstPY.charAt(uni - 19968)));
  },
  mkRslt: function(arr) {
    var arrRslt = [""];
    for (var i = 0, len = arr.length; i < len; i++) {
      var str = arr[i];
      var strlen = str.length;
      if (strlen == 1) {
        for (var k = 0; k < arrRslt.length; k++) {
          arrRslt[k] += str;
        }
      } else {
        var tmpArr = arrRslt.slice(0);
        arrRslt = [];
        for (k = 0; k < strlen; k++) {
          //复制一个相同的arrRslt  
          var tmp = tmpArr.slice(0);
          //把当前字符str[k]添加到每个元素末尾  
          for (var j = 0; j < tmp.length; j++) {
            tmp[j] += str.charAt(k);
          }
          //把复制并修改后的数组连接到arrRslt上  
          arrRslt = arrRslt.concat(tmp);
        }
      }
    }
    return arrRslt;
  },
  myMethod: {
    /**
     * 添加非标品
     */
    updateFb: function(m_supplier_id, m_num) {
      wx.request({
        url: that.globalData.url + 'api/Shopping/AddOrReduceNum',
        method: "POST",
        data: {
          supplier_id: m_supplier_id,
          good_id: 0,
          num: m_num,
          openid: that.globalData.openid
        },
        success: function(res) {}
      });
    },
    /**
     * 更新购物车中商品的数量
     */
    updateGood: function (m_supplier_id,m_b_supplier_id, m_good_id, m_num, m_remark, m_price,m_b_price,m_ku,is_aux,pr_unit,sub_unit_num,submit_price,history_price) { 
      if (/^0\d*$/.test(m_num) && m_num>0){   //当输入字符为整数且0开头
        m_num = m_num.replace(/^0+/, "")   //去掉前面的0
      };
      wx.request({
        url: that.globalData.url + 'api/Shopping/AddOrReduceNum',
        method: "POST",
        data: {
          supplier_id: m_supplier_id,
          b_supplier_id:m_b_supplier_id,
          good_id: m_good_id,
          num: m_num,
          openid: that.globalData.openid,
          remark: m_remark,
          true_price:m_price,
          single_price:m_b_price,
          is_ku:m_ku,  //1正常，2库存采购
          is_aux:is_aux,  //0不是辅助单位 ，1是辅助单位
          pr_unit:pr_unit, //下单商品的单位
          sub_unit_num:sub_unit_num,  //辅助单位换算比例（默认为1）
          submit_price:submit_price,
          history_price:history_price
        },
        success: function (res) {
          console.log(JSON.stringify(res.data));
          that.globalData.changyong_show=1;  //返回收藏页面时，是否刷新
        }
      });
    },
    /**
     * 更改订单中商品的数量
     */
    updataDingdanGood: function(m_good_id, m_order_id, m_num, m_remark) {
      if (/^0\d*$/.test(m_num) && m_num > 0) {   //当输入字符为整数且0开头
        m_num = m_num.replace(/^0+/, "")   //去掉前面的0
      };
      wx.request({
        url: that.globalData.url + 'api/Order/changeOrderNum',
        method: 'POST',
        data: {
          id: m_good_id,
          order_id: m_order_id,
          num: m_num,
          openid: that.globalData.openid,
          detail_remark: m_remark
        },
        success: function(res) {}
      })
    },
    /**
     * 更新常用数据
     */
    updateChangYongGood: function(m_supplier_id, m_good_id, m_num) {
      wx.request({
        url: that.globalData.url + 'api/Often/AddOrReduceNumToShopping',
        method: "POST",
        data: {
          supplier_id: m_supplier_id,
          good_id: m_good_id,
          num: m_num,
          openid: that.globalData.openid
        },
        success: function(res) {
          console.log(JSON.stringify(res.data));
        }
      });
    },
    /**
     * 更新购物车的商品数量
     */
    updateGoodNum: function (m_good_id, m_num, m_remark, submit_type) {
      wx.request({
        url: that.globalData.url + 'api/Shopping/changeMyShoppingNum',
        method: 'POST',
        data: {
          id: m_good_id,
          num: m_num,
          remark: m_remark
        },
        success: function(res) {
          that.globalData.changyong_show = 1;  //返回收藏页面时，是否刷新
          console.log(JSON.stringify(res.data));
        }
      })
    },
    /**
     * 更新中转库商品数量
     */
    updateMegerNum: function(m_good_id, m_num) {
      wx.request({
        url: that.globalData.url + 'api/Shopping/ChangeMergeNum',
        method: 'POST',
        data: {
          id: m_good_id,
          num: m_num
        },
        success: function(res) {
          console.log(JSON.stringify(res.data));
        }
      })
    },
    loading: function() {
      wx.showLoading({
        title: '加载中...',
      });
      setTimeout(function() {
        wx.hideLoading()
      }, 500);
    }
  },
  AppHttp: function(reqUrl, data, callBack) {
    that=this;
    that.globalData.task = wx.request({
      url: that.globalData.url + reqUrl,
      method: "POST",
      data: data,
      success: function (res) {
        callBack(res);
      }
    })  
  },
  UpAsso: function(reqUrl,callBack) {  //更新订单关联
    that=this;
    wx.request({
      url: 'https://www.xiaobangcai.com:8443/SmallDish/' + reqUrl,
      method: "GET",
      success: function (res) {
        callBack(res);
      }
    })  
  },
  // 去审批管理
  tocheck_manage:function(check_order_ids,purchase_order_ids,receipt_order_ids){
    wx.navigateTo({
      url: '/check_space/pages/check_manage/check_manage?check_order_ids='+check_order_ids+'&purchase_order_ids='+purchase_order_ids+'&receipt_order_ids='+receipt_order_ids
    });
  },
  get_count_list:function(seft){
    wx.request({
      url: that.globalData.url + 'api/Order/getCheckCount',
      method: 'POST',
      data: {
        openid: that.globalData.openid
      },
      success: function(res) {
        console.log(JSON.stringify(res.data));
        seft.setData({
          check_order_ids:res.data.check_order_ids,
          purchase_order_ids:res.data.purchase_order_ids,
          receipt_order_ids:res.data.receipt_order_ids
        });     
      }
    })
  },
  // 购物车抛物线动画
  screenSize: function() {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        var ww = res.windowWidth;
        var hh = res.windowHeight;
        that.globalData.ww = ww;
        that.globalData.hh = hh;
      }
    })
  },
  bezier: function(points, times) {
    // 0、以3个控制点为例，点A,B,C,AB上设置点D,BC上设置点E,DE连线上设置点F,则最终的贝塞尔曲线是点F的坐标轨迹。
    // 1、计算相邻控制点间距。
    // 2、根据完成时间,计算每次执行时D在AB方向上移动的距离，E在BC方向上移动的距离。
    // 3、时间每递增100ms，则D,E在指定方向上发生位移, F在DE上的位移则可通过AD/AB = DF/DE得出。
    // 4、根据DE的正余弦值和DE的值计算出F的坐标。
    // 邻控制AB点间距
    var bezier_points = [];
    var points_D = [];
    var points_E = [];
    // 线段AB的间距
    const DIST_AB = Math.sqrt(Math.pow(points[1]['x'] - points[0]['x'], 2) + Math.pow(points[1]['y'] - points[0]['y'], 2));
    // 邻控制BC点间距
    const DIST_BC = Math.sqrt(Math.pow(points[2]['x'] - points[1]['x'], 2) + Math.pow(points[2]['y'] - points[1]['y'], 2));
    // D每次在AB方向上移动的距离（每毫秒移动的距离）
    const EACH_MOVE_AD = DIST_AB / times;
    // E每次在BC方向上移动的距离 （每毫秒移动的距离）
    const EACH_MOVE_BE = DIST_BC / times;
    // 点AB的正切
    const TAN_AB = (points[1]['y'] - points[0]['y']) / (points[1]['x'] - points[0]['x']);
    // 点BC的正切
    const TAN_BC = (points[2]['y'] - points[1]['y']) / (points[2]['x'] - points[1]['x']);
    // 点AB的弧度值
    const RADIUS_AB = Math.atan(TAN_AB);
    // 点BC的弧度值
    const RADIUS_BC = Math.atan(TAN_BC);
    // 每次执行
    for (var i = 1; i <= times; i++) {
      // AD的距离
      var dist_AD = -EACH_MOVE_AD * i;
      // BE的距离
      var dist_BE = -EACH_MOVE_BE * i;
      // D点的坐标
      var point_D = {};
      point_D['x'] = dist_AD * Math.cos(RADIUS_AB) + points[0]['x'];
      point_D['y'] = dist_AD * Math.sin(RADIUS_AB) + points[0]['y'];
      points_D.push(point_D);
      // E点的坐标
      var point_E = {};
      point_E['x'] = dist_BE * Math.cos(RADIUS_BC) + points[1]['x'];
      point_E['y'] = dist_BE * Math.sin(RADIUS_BC) + points[1]['y'];
      points_E.push(point_E);
      // 此时线段DE的正切值
      var tan_DE = (point_E['y'] - point_D['y']) / (point_E['x'] - point_D['x']);
      // tan_DE的弧度值
      var radius_DE = Math.atan(tan_DE);
      // 地市DE的间距
      var dist_DE = Math.sqrt(Math.pow((point_E['x'] - point_D['x']), 2) + Math.pow((point_E['y'] - point_D['y']), 2));
      // 此时DF的距离
      var dist_DF = (dist_AD / DIST_AB) * dist_DE;
      // 此时DF点的坐标
      var point_F = {};
      point_F['x'] = dist_DF * Math.cos(radius_DE) + point_D['x'];
      point_F['y'] = dist_DF * Math.sin(radius_DE) + point_D['y'];
      bezier_points.push(point_F);
    }
    return {
      'bezier_points': bezier_points
    };
  }
})